// pages/adddog/adddog.js
import {
  ajax,
  src,
  util
} from "../../utils/util.js";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    uqid: "",
    dogphoto: [],
    stylelist: ["泰迪", "柯基", "金毛", "边牧", "斗牛", "二哈", "猫猫", "其他"],
    agelist: ["一岁", "两岁", "三岁", "四岁", "五岁", "六岁", "七岁", "八岁", "九岁", "十岁", "十一岁", "十二岁", "十三岁", "十四岁", "十五岁"],
    nicheng: "",
    xingge: "",
    jianjie: "",
    age: "",
    style: "",
    sex: 1,
    jueyu: 0,
    picture:"",

    canselect:"",
    id:""
  },

  selectsex: function (e) {
    var index = e.currentTarget.dataset.index;
    this.setData({
      sex: index
    })
  },
  selectjueyu: function (e) {
    var index = e.currentTarget.dataset.index;
    this.setData({
      jueyu: index
    })
  },

  getnicheng: function (e) {
    // console.log(e.detail.value)
    this.setData({
      nicheng: e.detail.value
    })
  },
  getxingge: function (e) {
    // console.log(e.detail.value)
    this.setData({
      xingge: e.detail.value
    })
  },
  getjianjie: function (e) {
    // console.log(e.detail.value)
    this.setData({
      jianjie: e.detail.value
    })
  },

  // 选择年龄
  bindPickerChange: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      age: Number(e.detail.value)+1
    })
  },
  // 选择种类
  bindstyleChange: function (e) {
    this.setData({
      style: this.data.stylelist[e.detail.value]
    })
  },

  // 删除已选照片
  handleDelRomm(e) {
    let eindex = e.currentTarget.dataset.index; //点击的坐标
    console.log(eindex)
    let arr = this.data.dogphoto;
    arr.splice(eindex, 1)
    this.setData({
      dogphoto: arr
    });

    this.computercanselect()
  },

  handleDelhistory(e){
    var url = e.currentTarget.dataset.url
    ajax("/api/user/picture_delete", {
      data: {
        uqid: this.data.uqid,
        petid: this.data.id,
        picture_name:url
      },
      header: {
        'Accept': 'application/json', // 默认值
      },
      method: 'DELETE'
    }, res => {
      console.log(res);
      if (res.error == 0) {//获取进展 pid
        this.getdotallmsg()
      }
    })

  },

  // 点击添加
  uploadMedical: function () {
    var uqid = this.data.uqid;
    console.log(uqid)
    var that = this
    wx.showActionSheet({
      itemList: ['从相册选取', '拍照'],
      success(res) {
        console.log(res.tapIndex)
        var index = res.tapIndex;

        var dogphoto = that.data.dogphoto;
        if (index == 0) {

          let num = that.data.canselect; //一次最大上传九张

          wx.chooseImage({
            count: num,
            sizeType: ['original', 'compressed'],
            sourceType: ['album'],
            success(res) {
              console.log(res)
              // tempFilePath可以作为img标签的src属性显示图片
              const tempFilePaths = res.tempFilePaths;
              console.log(tempFilePaths)

              for (let i = 0; i < tempFilePaths.length; i++) {
                dogphoto.push(tempFilePaths[i])
              }
              that.setData({
                dogphoto: dogphoto
              });
              that.computercanselect()
            }
          })
        } else if (index == 1) {
          wx.chooseImage({
            count: 1,
            sizeType: ['original', 'compressed'],
            sourceType: ['camera'],
            success(res) {
              console.log(res)
              // tempFilePath可以作为img标签的src属性显示图片

              var dogphoto = that.data.dogphoto;

              const tempFilePaths = res.tempFilePaths;

              dogphoto.push(tempFilePaths[0])
              that.setData({
                dogphoto: dogphoto
              });
              that.computercanselect()
            }
          })
        }

      },
      fail(res) {
        console.log(res.errMsg)
      }
    })

  },

  tijiaopetmsg: function () {

    ajax("/api/user/my_pet_edit", {
      data: {
        uqid: this.data.uqid,

        id: this.data.id,

        nickname: this.data.nicheng,
        sex: this.data.sex,
        is_sterilization: Number(this.data.jueyu),
        age: this.data.age,
        character: this.data.xingge,
        introduction: this.data.jianjie,
        type_show: this.data.style
      },
      header: {
        'Accept': 'application/json', // 默认值
      },
      method: 'PUT'
    }, res => {
      console.log(res);
      if (res.error == 0) {//获取进展 pid

        var petid = this.data.id
        var dogphoto = this.data.dogphoto;

        if (dogphoto.length!=0){
          this.uploadimg({
            url: src + '/api/user/picture_uplode', //这里是你图片上传的接口
            path: dogphoto,//这里是选取的图片的地址数组       
            petid: petid
          });
        }else{
          this.toback()
        }
      }
    })


  },

  // 多文件上传
  uploadimg(data) {
    var that = this
    var uqid = that.data.uqid
    var i = data.i ? data.i : 0//当前上传的哪张图片

    var success = data.success ? data.success : 0 //上传成功的个数
    var fail = data.fail ? data.fail : 0 //上传失败的个数
    console.log(i)

    wx.showLoading({
      title: '上传中',
    })
    wx.uploadFile({
      url: data.url,
      filePath: data.path[i],
      name: 'picture', //这里根据自己的实际情况改
      formData: {
        uqid: uqid,
        petid: data.petid
      }, //这里是上传图片时一起上传的数据
      header: { "Content-Type": "multipart/form-data" },
      success(resU) {
        success++;
      },
      fail: (res) => {
        fail++; //图片上传失败，图片上传失败的变量+1
        console.log('fail:' + i + "fail:" + fail);
      },
      complete: () => {
        console.log(i);
        i++; //这个图片执行完上传后，开始上传下一张            
        if (i == data.path.length) { //当图片传完时，停止调用   
          wx.hideLoading();
          console.log('执行完毕');
          console.log('成功：' + success + " 失败：" + fail)
          // return ('成功：' + success + " 失败：" + fail);

          wx.showToast({
            title: "上传成功",
            icon: 'none',
            duration: 3000,
            success: this.toback
          })

        } else { //若图片还没有传完，则继续调用函数     
          wx.hideLoading();
          console.log(i);
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.uploadimg(data);
        }
      }
    })
  },

  toback: function () {
    wx.navigateBack({
      delta: 1
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var id = options.id
    var uqid = wx.getStorageSync("uqid");
    this.setData({
      id: id,
      uqid: uqid
    })
    this.getdotallmsg()
  },

  getdotallmsg: function () {
    ajax("/api/user/my_pet_show", {
      data: {
        uqid: this.data.uqid,
        id: this.data.id
      },
      header: {
        'Accept': 'application/json', // 默认值
      },
      method: 'get'
    }, res => {
      console.log(res);
      if (res.error == 0) {//获取进展 pid
        this.setData({
          nicheng: res.data.nickname,
          xingge: res.data.character,
          jianjie: res.data.introduction ,
          age: res.data.age,
          style: res.data.type_show ,
          sex: res.data.sex,
          jueyu: res.data.is_sterilization,

          picture: res.data.picture,
        })

        this.computercanselect()
      }
    })
  },

  computercanselect:function(){
    if (this.data.dogphoto) {
      var canselect = 9 - this.data.dogphoto.length - this.data.picture.length
    }
    else {
      var canselect = 9 - this.data.picture.length
    }
    this.setData({
      canselect: canselect
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})